package io.kimmking.gateway.ratelimiter;

import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter;
import org.springframework.cloud.gateway.support.StatefulConfigurable;
import org.springframework.util.Assert;
import reactor.core.publisher.Mono;

import java.util.Collections;
import java.util.Map;


/**
 * 接口级别粒度的限流控制
 * @param <C>
 */
public interface RateLimiterPerInterfacePath<C> extends StatefulConfigurable<C> {

    Mono<RateLimiter.Response> isAllowed(String routeId, String id, String requestPath);

    public static class Response {
        private final boolean allowed;
        private final long tokensRemaining;
        private final Map<String, String> headers;

        public Response(boolean allowed, Map<String, String> headers) {
            this.allowed = allowed;
            this.tokensRemaining = -1L;
            Assert.notNull(headers, "headers may not be null");
            this.headers = headers;
        }

        public boolean isAllowed() {
            return this.allowed;
        }

        public Map<String, String> getHeaders() {
            return Collections.unmodifiableMap(this.headers);
        }

        public String toString() {
            StringBuffer sb = new StringBuffer("Response{");
            sb.append("allowed=").append(this.allowed);
            sb.append(", headers=").append(this.headers);
            sb.append(", tokensRemaining=").append(this.tokensRemaining);
            sb.append('}');
            return sb.toString();
        }
    }
}
